<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="员工编码" prop="partyId">
        <el-input
          v-model="queryParams.partyId"
          placeholder="请输入员工编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批状态" prop="approvalState">
        <el-input
          v-model="queryParams.approvalState"
          placeholder="请输入审批状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ehr:cust_attend_record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ehr:cust_attend_record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ehr:cust_attend_record:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ehr:cust_attend_record:export']"
        >导出</el-button>
      </el-col>

      <div class="upload-file">
        <el-upload
          :action="uploadFileUrl"
          :before-upload="handleBeforeUpload"
          :limit="limit"
          :on-error="handleUploadError"
          :on-exceed="handleExceed"
          :on-success="handleUploadSuccess"
          :show-file-list="true"
          :headers="headers"
          class="upload-file-uploader"
          ref="upload"
        >
          <!-- 上传按钮 -->
          <el-button size="mini" type="primary">上传数据</el-button>
          <!-- 上传提示 -->
          <div class="el-upload__tip" slot="tip" v-if="showTip">
            请上传
            <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
            <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
            的文件
          </div>
        </el-upload>

        <!-- 文件列表 -->
        <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
          <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
            <el-link :href="`${baseUrl}${file.url}`" :underline="false" target="_blank">
              <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
            </el-link>
            <div class="ele-upload-list__item-content-action">
              <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
            </div>
          </li>
        </transition-group>
      </div>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cust_attend_recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据ID" align="center" prop="dataId" />
      <el-table-column label="员工编码" align="center" prop="partyId" />
      <el-table-column label="手机号" align="center" prop="mobilePhone" />
      <el-table-column label="职员" align="center" prop="employeeName" />
      <el-table-column label="打卡时间" align="center" prop="formalStartTime" />
      <el-table-column label="打卡点" align="center" prop="formalStartPlace" />
      <el-table-column label="审批状态" align="center" prop="approvalState" />
      <el-table-column label="数据状态" align="center" prop="dataState" width="180" :formatter="dataStateFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleDetail(scope.row)"
            v-hasPermi="['ehr:cust_attend_record:detail']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ehr:cust_attend_record:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ehr:cust_attend_record:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考勤数据中间表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" v-bind:disabled = detailFlag>
        <el-row>
          <el-col :span="12" >
            <el-form-item label="员工编码" prop="partyId">
                <el-input v-model="form.partyId" placeholder="请输入员工编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="手机号" prop="mobilePhone">
                <el-input v-model="form.mobilePhone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row >
        <el-row>
          <el-col :span="12" >
            <el-form-item label="职员" prop="employeeName">
                <el-input v-model="form.employeeName" placeholder="请输入职员" />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="所属组织" prop="organization">
                <el-input v-model="form.organization" placeholder="请输入所属组织" />
            </el-form-item>
          </el-col>
        </el-row >
        <el-row>
        </el-row >
        <el-row>
          <el-col :span="12" >
              <el-form-item label="打卡点" prop="formalStartPlace">
                  <el-input v-model="form.formalStartPlace" type="textarea" placeholder="请输入内容" />
              </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="审批状态" prop="approvalState">
                <el-input v-model="form.approvalState" placeholder="请输入审批状态" />
            </el-form-item>
          </el-col>
        </el-row >
        <el-row>
          <el-col :span="12" >
            <el-form-item label="打卡来源" prop="attendSource">
                <el-input v-model="form.attendSource" placeholder="请输入打卡来源" />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="单据状态" prop="documentState">
                <el-input v-model="form.documentState" placeholder="请输入单据状态" />
            </el-form-item>
          </el-col>
        </el-row >
        <el-row>
          <el-col :span="12" >
            <el-form-item label="原因" prop="reason">
                <el-input v-model="form.reason" placeholder="请输入原因" />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row >
        <el-row>
          <el-col :span="12" >
            <el-form-item label="生成时间" prop="generatedTime">
                <el-input v-model="form.generatedTime" placeholder="请输入生成时间" />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="修改时间" prop="modifiedTime">
                <el-input v-model="form.modifiedTime" placeholder="请输入修改时间" />
            </el-form-item>
          </el-col>
        </el-row >
        <el-row>
          <el-col :span="12" >
            <el-form-item label="操作人" prop="operator">
                <el-input v-model="form.operator" placeholder="请输入操作人" />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="当前审批人" prop="approvalName">
                <el-input v-model="form.approvalName" placeholder="请输入当前审批人" />
            </el-form-item>
          </el-col>
        </el-row >
        <el-row>
          <el-col :span="12" >
            <el-form-item label="考勤机ID" prop="attendanceMachineId">
                <el-input v-model="form.attendanceMachineId" placeholder="请输入考勤机ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
                <el-form-item label="数据状态">
                    <el-radio-group v-model="form.dataState">
                        <el-radio
                          v-for="dict in dataStateOptions"
                          :key="dict.enumCode"
                          :label="dict.enumCode"
                        >{{dict.description}}</el-radio>
                    </el-radio-group>
                </el-form-item>
          </el-col>
        </el-row >
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="editFlag" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { listCust_attend_record, getCust_attend_record, delCust_attend_record, addCust_attend_record, updateCust_attend_record } from "@/api/ehr/cust_attend_record";

export default {
  name: "Cust_attend_record",
  props: {
    // 上传考勤数据-数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 上传考勤数据-大小限制(MB)
    fileSize: {
      type: Number,
      default: 10,
    },
    // 上传考勤数据-文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["xls", "xlsx"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      // 上传文件的服务器地址
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/ehr/cust_attend_record/upload', 
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考勤数据中间表表格数据
      cust_attend_recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 数据状态业务字典
      dataStateOptions: [],
      // 操作标识,用于区分是新增还是修改
      updateFlag: false,
      // 操作标识,用于区分是详情
      detailFlag: false,
      // 操作标识,用于区分编辑状态
      editFlag: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: "", // 排序字段
        isAsc:"", // 升序或降序 大写的 ASC或DESC,为空代表升序
        partyId: null,
        formalStartTime: null,
        approvalState: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    // 数据状态业务字典
    this.getEnumDicts("COMMON_Y_N").then((response) => {
      this.dataStateOptions = response.data;
    });
    this.getList();
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading()
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      this.$modal.msgSuccess("上传文件成功");
      this.$modal.closeLoading();

      // this.uploadList.push({ name: res.fileName, url: res.fileName });
      // if (this.uploadList.length === this.number) {
      //   this.$modal.msgSuccess("上传文件成功");
      //   this.$modal.closeLoading();
      // }
    },
     dataStateFormat(row, column) {
      let val = null;
      this.dataStateOptions.forEach((item, index) => {
        if (row.dataState === item.enumCode) {
          val = item.description;
        }
      });
      return val;
    },
    /** 查询考勤数据中间表列表 */
    getList() {
      this.loading = true;
      listCust_attend_record(this.queryParams).then(response => {
        this.cust_attend_recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        dataId: null,
        partyId: null,
        mobilePhone: null,
        employeeName: null,
        organization: null,
        formalStartTime: null,
        formalStartPlace: null,
        approvalState: null,
        attendSource: null,
        documentState: null,
        reason: null,
        remark: null,
        generatedTime: null,
        modifiedTime: null,
        operator: null,
        approvalName: null,
        attendanceMachineId: null,
        dataState: "0",
        lastUpdatedStamp: null,
        lastUpdatedTxStamp: null,
        createdStamp: null,
        createdTxStamp: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dataId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.editFlag = true,
      this.updateFlag = false;
      this.detailFlag = false;
      this.reset();
      this.open = true;
      this.title = "添加考勤数据中间表";
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.editFlag = false,
      this.updateFlag = false;
      this.detailFlag = true;
      this.reset();
      const dataId = row.dataId || this.ids
      getCust_attend_record(dataId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "考勤数据中间表详情";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.editFlag = true;
      this.updateFlag = true;
      this.detailFlag = false;
      this.reset();
      const dataId = row.dataId || this.ids
      getCust_attend_record(dataId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改考勤数据中间表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.dataId != null && this.updateFlag) {
            updateCust_attend_record(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCust_attend_record(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dataIds = row.dataId || this.ids;
      this.$modal.confirm('是否确认删除考勤数据中间表编号为"' + dataIds + '"的数据项？').then(function() {
        return delCust_attend_record(dataIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ehr/cust_attend_record/export', {
        ...this.queryParams
      }, `cust_attend_record_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
